﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.IO;


namespace Controls
{
    /// <summary>
    /// Summary description for SiteCategoryList
    /// </summary>
    public class RecentlyViewedProducts : System.Web.UI.Control
    {
        const string SESSION_KEY = "SessionRequestProducts";

        public RecentlyViewedProducts()
        {
            long prodID = 0;

            if (HttpContext.Current.Request.QueryString["id"] != null)
            {
                long.TryParse(HttpContext.Current.Request.QueryString["id"], out prodID);                
            }


            if (HttpContext.Current.Session[SESSION_KEY] == null)
            {
                HttpContext.Current.Session.Add(SESSION_KEY, new List<AwinDotNet.Product>());
            }




            if (prodID > 0)
            {
                AddProduct(prodID);
            }

        }

        private void AddProduct(long id)
        {
     
            AwinDotNet.Product p = AwinDotNet.AwinAPI.Products.GetProduct(id);

            if (p != null)
            {
 
                List<AwinDotNet.Product> prods = (List<AwinDotNet.Product>)HttpContext.Current.Session[SESSION_KEY];

                if (!prods.Contains(p))
                {
                    prods.Insert(0, p);
                }

                if (prods.Count > 20)
                {
                    prods.RemoveRange(20, prods.Count - 20);
                }
            }

            
        }



        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);


            List<AwinDotNet.Product> prods = (List<AwinDotNet.Product>)HttpContext.Current.Session[SESSION_KEY];


            HtmlGenericControl ul = new HtmlGenericControl("ul");
            ul.ID = "RecentProducts";

            foreach (AwinDotNet.Product p in prods )
            {
                HtmlGenericControl li = new HtmlGenericControl("li");
                HtmlAnchor anc = new HtmlAnchor();
                anc.HRef = string.Format("showproduct.aspx?id={0}", p.ID);
                anc.InnerHtml = p.Name;
                anc.Title = p.Name;

                li.Controls.Add(anc);
                ul.Controls.Add(li);
            }

            System.IO.StringWriter sw = new System.IO.StringWriter();
            ul.RenderControl(new HtmlTextWriter(sw));

            writer.Write(sw.ToString());

        }

    }
}